<template>
  <div class="products-page">
    <div class="container">
      <!-- 页面标题和搜索 -->
      <div class="page-header">
        <div class="page-title">
          <h1>商品列表</h1>
          <p>发现最适合您爱宠的商品</p>
        </div>
        
        <div class="search-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索商品..."
            size="large"
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <div class="products-content">
        <!-- 侧边栏筛选 -->
        <aside class="filters-sidebar">
          <div class="filter-section">
            <h3 class="filter-title">商品分类</h3>
            <div class="filter-options">
              <div 
                v-for="category in categories"
                :key="category.value"
                class="filter-option"
                :class="{ active: selectedCategory === category.value }"
                @click="filterByCategory(category.value)"
              >
                <span>{{ category.label }}</span>
                <span class="count">({{ category.count }})</span>
              </div>
            </div>
          </div>

          <div class="filter-section">
            <h3 class="filter-title">价格范围</h3>
            <div class="price-filter">
              <el-slider
                v-model="priceRange"
                range
                :min="0"
                :max="1000"
                :step="10"
                @change="filterByPrice"
              />
              <div class="price-display">
                ¥{{ priceRange[0] }} - ¥{{ priceRange[1] }}
              </div>
            </div>
          </div>

          <div class="filter-section">
            <h3 class="filter-title">排序方式</h3>
            <el-select 
              v-model="sortBy" 
              placeholder="选择排序方式"
              @change="handleSort"
              style="width: 100%"
            >
              <el-option label="默认排序" value="default" />
              <el-option label="价格从低到高" value="price-asc" />
              <el-option label="价格从高到低" value="price-desc" />
              <el-option label="最新上架" value="newest" />
              <el-option label="销量最高" value="popular" />
            </el-select>
          </div>

          <el-button 
            type="danger" 
            plain 
            @click="clearFilters"
            style="width: 100%; margin-top: 20px;"
          >
            清除筛选
          </el-button>
        </aside>

        <!-- 商品列表 -->
        <main class="products-main">
          <div class="products-toolbar">
            <div class="results-info">
              <span>找到 {{ filteredProducts.length }} 件商品</span>
            </div>
            
            <div class="view-options">
              <el-button-group>
                <el-button 
                  :type="viewMode === 'grid' ? 'primary' : 'default'"
                  :icon="Grid"
                  @click="viewMode = 'grid'"
                />
                <el-button 
                  :type="viewMode === 'list' ? 'primary' : 'default'"
                  :icon="List"
                  @click="viewMode = 'list'"
                />
              </el-button-group>
            </div>
          </div>

          <!-- 商品网格/列表 -->
          <div 
            v-if="filteredProducts.length > 0"
            class="products-container"
            :class="{ 'list-view': viewMode === 'list' }"
          >
            <ProductCard 
              v-for="product in paginatedProducts"
              :key="product.id"
              :product="product"
              :class="{ 'list-card': viewMode === 'list' }"
            />
          </div>

          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-empty description="没有找到相关商品">
              <el-button type="primary" @click="clearFilters">清除筛选条件</el-button>
            </el-empty>
          </div>

          <!-- 分页 -->
          <div v-if="filteredProducts.length > 0" class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="filteredProducts.length"
              layout="prev, pager, next, jumper"
              @current-change="handlePageChange"
            />
          </div>
        </main>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import ProductCard from '@/components/ProductCard.vue'
import { 
  Search, 
  Grid, 
  List 
} from '@element-plus/icons-vue'

export default {
  name: 'ProductsPage',
  components: {
    ProductCard,
    Search,
    Grid,
    List
  },
  setup() {
    const route = useRoute()
    
    // 响应式数据
    const searchQuery = ref('')
    const selectedCategory = ref('all')
    const priceRange = ref([0, 1000])
    const sortBy = ref('default')
    const viewMode = ref('grid')
    const currentPage = ref(1)
    const pageSize = ref(12)
    
    // 分类数据
    const categories = ref([
      { label: '全部商品', value: 'all', count: 24 },
      { label: '宠物食品', value: 'food', count: 8 },
      { label: '玩具用品', value: 'toys', count: 6 },
      { label: '护理用品', value: 'care', count: 5 },
      { label: '服装配饰', value: 'clothing', count: 3 },
      { label: '其他用品', value: 'accessories', count: 2 }
    ])
    
    // 所有商品数据
    const allProducts = ref([
      // 宠物食品类 (8个)
      {
        id: 1,
        name: '进口高端猫粮',
        description: '精选优质原料，营养均衡，呵护猫咪健康成长',
        price: 299,
        originalPrice: 399,
        image: require('@/assets/images/AD0I9ruEDBAEGAAg6Z-B_wUojMjq3QYwgAY4gAY_400x400.png'),
        category: 'food',
        sales: 1250,
        isNew: false
      },
      {
        id: 2,
        name: '天然狗粮',
        description: '无谷物配方，富含蛋白质，适合成犬日常营养需求',
        price: 256,
        originalPrice: 320,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSvridDH4DtOIq-20xmVkkZK0BhhBKHGYHzuQ&s',
        category: 'food',
        sales: 987,
        isNew: false
      },
      {
        id: 3,
        name: '宠物营养零食',
        description: '天然制作，训练奖励首选，增强宠物与主人互动',
        price: 45,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgsZ-B_wUom8Kd-wQwgAY4gAY_400x400.png'),
        category: 'food',
        sales: 1100,
        isNew: false
      },
      {
        id: 4,
        name: '幼犬专用奶粉',
        description: '专为幼犬设计，富含DHA，促进大脑发育',
        price: 89,
        image: '',
        category: 'food',
        sales: 445,
        isNew: true
      },
      {
        id: 5,
        name: '猫咪湿粮罐头',
        description: '新鲜肉质，口感丰富，补充日常水分摄入',
        price: 25,
        image: require('@/assets/images/AD0I9ruEDBAEGAAg_p7B_wUoyPiemAYwgAY4gAY_400x400.png'),
        category: 'food',
        sales: 789,
        isNew: false
      },
      {
        id: 6,
        name: '宠物维生素片',
        description: '全面营养补充，提升免疫力，保持宠物活力',
        price: 67,
        image: '',
        category: 'food',
        sales: 323,
        isNew: false
      },
      {
        id: 7,
        name: '有机猫草',
        description: '天然种植，帮助猫咪消化，清洁口腔，缓解压力',
        price: 15,
        image: '',
        category: 'food',
        sales: 156,
        isNew: true
      },
      {
        id: 8,
        name: '宠物钙片',
        description: '强化骨骼发育，适合成长期和老年宠物补钙',
        price: 56,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgw4jB_wUohbDYwwcwgAY4gAY_400x400.png'),
        category: 'food',
        sales: 234,
        isNew: false
      },
      
      // 玩具用品类 (6个)
      {
        id: 9,
        name: '智能互动玩具',
        description: '声光互动，自动运动，激发宠物游戏天性',
        price: 129,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSN38DljChTCbmF6KcnBd-tgFUTXsFqKfwOSA&s',
        category: 'toys',
        sales: 890,
        isNew: true
      },
      {
        id: 10,
        name: '电动逗猫棒',
        description: '自动摆动，解放双手，让猫咪尽情玩耍',
        price: 156,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSpACISWWljMbo2q4jrUWfPGw81q-DQFtupjw&s',
        category: 'toys',
        sales: 332,
        isNew: true
      },
      {
        id: 11,
        name: '宠物飞盘',
        description: '户外运动首选，增强体质，培养服从性',
        price: 35,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgqqDB_wUo2IeurwYwgAY4gAY_400x400.png'),
        category: 'toys',
        sales: 567,
        isNew: false
      },
      {
        id: 13,
        name: '发声球玩具',
        description: '内置发声器，吸引注意力，适合各种犬类',
        price: 28,
        image: '',
        category: 'toys',
        sales: 234,
        isNew: false
      },
      {
        id: 14,
        name: '猫咪抓板',
        description: '保护家具，磨爪利器，天然剑麻材质',
        price: 89,
        originalPrice: 120,
        image:'',
        category: 'toys',
        sales: 678,
        isNew: false
      },
      
      // 护理用品类 (5个)
      {
        id: 16,
        name: '宠物美容工具套装',
        description: '专业梳理，修剪指甲，让宠物更美丽',
        price: 145,
        image: '',
        category: 'care',
        sales: 234,
        isNew: true
      },
      {
        id: 17,
        name: '宠物护眼清洁液',
        description: '温和清洁眼部分泌物，预防眼部疾病',
        price: 45,
        image: '',
        category: 'care',
        sales: 345,
        isNew: false
      },
      {
        id: 19,
        name: '宠物指甲剪',
        description: '锋利耐用，人体工学设计，修剪更轻松',
        price: 29,
        image: '',
        category: 'care',
        sales: 123,
        isNew: false
      },
      
      // 服装配饰类 (3个)
      {
        id: 21,
        name: '宠物雨衣',
        description: '防水透气，雨天出行必备，多色可选',
        price: 45,
        image: require('@/assets/images/AD0I9ruEDBAEGAAg7IXB_wUolP6qlQQwgAY4gAY_400x400.png'),
        category: 'clothing',
        sales: 167,
        isNew: true
      },
      {
        id: 22,
        name: '宠物领结',
        description: '精致装饰，绅士风范，节日聚会首选',
        price: 25,
        image: '',
        category: 'clothing',
        sales: 89,
        isNew: false
      },
      
      // 其他用品类 (2个)
      {
        id: 23,
        name: '豪华宠物窝',
        description: '柔软舒适，四季适用，给宠物温暖的家',
        price: 188,
        image: '',
        category: 'accessories',
        sales: 445,
        isNew: true
      },
      {
        id: 24,
        name: '智能饮水器',
        description: '自动循环过滤，保持水质新鲜，鼓励多喝水',
        price: 156,
        originalPrice: 200,
        image: '',
        category: 'accessories',
        sales: 298,
        isNew: true
      }
    ])
    
    // 筛选后的商品
    const filteredProducts = computed(() => {
      let products = [...allProducts.value]
      
      // 按分类筛选
      if (selectedCategory.value !== 'all') {
        products = products.filter(p => p.category === selectedCategory.value)
      }
      
      // 按搜索关键词筛选
      if (searchQuery.value.trim()) {
        const query = searchQuery.value.toLowerCase().trim()
        products = products.filter(p => 
          p.name.toLowerCase().includes(query) || 
          p.description.toLowerCase().includes(query)
        )
      }
      
      // 按价格筛选
      products = products.filter(p => 
        p.price >= priceRange.value[0] && p.price <= priceRange.value[1]
      )
      
      // 排序
      switch (sortBy.value) {
        case 'price-asc':
          products.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          products.sort((a, b) => b.price - a.price)
          break
        case 'newest':
          products.sort((a, b) => b.isNew - a.isNew)
          break
        case 'popular':
          products.sort((a, b) => b.sales - a.sales)
          break
        default:
          // 默认排序
          break
      }
      
      return products
    })
    
    // 分页后的商品
    const paginatedProducts = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredProducts.value.slice(start, end)
    })
    
    // 方法
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const filterByCategory = (category) => {
      selectedCategory.value = category
      currentPage.value = 1
    }
    
    const filterByPrice = () => {
      currentPage.value = 1
    }
    
    const handleSort = () => {
      currentPage.value = 1
    }
    
    const clearFilters = () => {
      searchQuery.value = ''
      selectedCategory.value = 'all'
      priceRange.value = [0, 1000]
      sortBy.value = 'default'
      currentPage.value = 1
    }
    
    const handlePageChange = (page) => {
      currentPage.value = page
      // 滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
    
    // 监听路由变化，处理查询参数
    watch(() => route.query, (newQuery) => {
      // 处理分类参数
      if (newQuery.category && newQuery.category !== selectedCategory.value) {
        selectedCategory.value = newQuery.category
      }
      
      // 处理排序参数
      if (newQuery.sort && newQuery.sort !== sortBy.value) {
        sortBy.value = newQuery.sort
      }
    }, { immediate: true, deep: true })
    
    onMounted(() => {
      // 处理初始查询参数
      const categoryFromQuery = route.query.category
      const sortFromQuery = route.query.sort
      
      if (categoryFromQuery) {
        selectedCategory.value = categoryFromQuery
      }
      
      if (sortFromQuery) {
        sortBy.value = sortFromQuery
      }
    })
    
    return {
      searchQuery,
      selectedCategory,
      priceRange,
      sortBy,
      viewMode,
      currentPage,
      pageSize,
      categories,
      filteredProducts,
      paginatedProducts,
      handleSearch,
      filterByCategory,
      filterByPrice,
      handleSort,
      clearFilters,
      handlePageChange,
      // Element Plus icons
      Grid,
      List
    }
  }
}
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 40px 0;
}

.page-header {
  background: white;
  padding: 40px 0;
  margin-bottom: 40px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-title {
  text-align: center;
  margin-bottom: 30px;
}

.page-title h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.page-title p {
  color: #666;
  font-size: 1.1rem;
}

.search-section {
  max-width: 500px;
  margin: 0 auto;
}

.search-input {
  border-radius: 25px;
}

.products-content {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 40px;
}

/* 筛选侧边栏 */
.filters-sidebar {
  background: white;
  padding: 30px;
  border-radius: 12px;
  height: fit-content;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.filter-section {
  margin-bottom: 30px;
}

.filter-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.filter-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-option:hover {
  background: #f0f9ff;
  color: #FF8C00;
}

.filter-option.active {
  background: #FF8C00;
  color: white;
}

.count {
  font-size: 0.9rem;
  opacity: 0.8;
}

.price-filter {
  padding: 0 10px;
}

.price-display {
  text-align: center;
  margin-top: 15px;
  font-weight: 500;
  color: #FF8C00;
}

/* 商品主区域 */
.products-main {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.products-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.results-info {
  color: #666;
  font-size: 0.95rem;
}

.products-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.products-container.list-view {
  grid-template-columns: 1fr;
  gap: 20px;
}

.list-card {
  display: flex;
  flex-direction: row;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .products-content {
    grid-template-columns: 1fr;
  }
  
  .filters-sidebar {
    order: 2;
    padding: 20px;
  }
  
  .products-main {
    order: 1;
  }
}

@media (max-width: 768px) {
  .products-page {
    padding: 20px 0;
  }
  
  .page-header {
    padding: 30px 20px;
    margin-bottom: 20px;
  }
  
  .page-title h1 {
    font-size: 2rem;
  }
  
  .products-content {
    gap: 20px;
  }
  
  .products-container {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .products-toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .view-options {
    align-self: center;
  }
}

@media (max-width: 480px) {
  .page-title h1 {
    font-size: 1.6rem;
  }
  
  .search-section {
    padding: 0 20px;
  }
  
  .filters-sidebar,
  .products-main {
    padding: 20px 15px;
  }
}
</style>
